package net.sudot.chess.web.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对不同配置的url访问映射不同基础路径
 *
 * @author tangjialin on 2018-01-30.
 */
public class ViewInterceptor implements HandlerInterceptor {

    private String prefix;
    private String exclude;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (modelAndView == null) { return; }
        String viewName = modelAndView.getViewName();
        if (viewName == null || viewName.contains(":")) { return; }
        if (exclude == null || viewName.startsWith(exclude)) { return; }
        modelAndView.setViewName(prefix + viewName);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    public String getPrefix() {
        return prefix;
    }

    public ViewInterceptor setPrefix(String prefix) {
        this.prefix = prefix;
        return this;
    }

    public String getExclude() {
        return exclude;
    }

    public ViewInterceptor setExclude(String exclude) {
        this.exclude = exclude;
        return this;
    }
}
